package com.huaishushu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huaishushu.common.BaseContext;
import com.huaishushu.common.CustomException;
import com.huaishushu.dto.OrdersDto;
import com.huaishushu.entity.*;
import com.huaishushu.mapper.OrdersMapper;
import com.huaishushu.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ChiBaoBaoHuaiShuShu
 * @since 2023-05-28
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IAddressBookService addressBookService;

    @Autowired
    private IShoppingCartService shoppingCartService;

    @Override
    @Transactional
    public void submit(Orders orders) {

        //获取当前的用户信息
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);

        //获取当前的地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址有误，无法下单，请检查地址是否正确！！！");
        }

        //获取登录用户购物车内的商品信息
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new CustomException("购物车为空，无法下单！！！");
        }

        //总金额，AtomicInteger类型不用担心线程的问题。
        AtomicInteger amount = new AtomicInteger(0);
        //订单号
        long orderId = IdWorker.getId();

        //为订单详情表的对象赋值，进而获得List<OrderDetail>，用来给订单详情表插入数据
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            //订单号
            orderDetail.setOrderId(orderId);
            //商品数
            orderDetail.setNumber(item.getNumber());
            //商品口味
            orderDetail.setDishFlavor(item.getDishFlavor());
            //菜品id
            orderDetail.setDishId(item.getDishId());
            //套餐id
            orderDetail.setSetmealId(item.getSetmealId());
            //菜品或商品名称
            orderDetail.setName(item.getName());
            //商品图片
            orderDetail.setImage(item.getImage());
            //商品单价
            orderDetail.setAmount(item.getAmount());
            //计算总金额，multiply（作为为相乘）
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            return orderDetail;
        }).collect(Collectors.toList());


        //为订单对象Orders orders赋值，为插入订单表做准备
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        //创建时间
        orders.setOrderTime(LocalDateTime.now());
        //付款时间
        orders.setCheckoutTime(LocalDateTime.now());
        //支付状态
        orders.setStatus(2);
        //总金额
        orders.setAmount(new BigDecimal(amount.get()));
        //用户id（用户）
        orders.setUserId(userId);
        //用户名称
        orders.setUserName(user.getName());
        //收货人（地址）
        orders.setConsignee(addressBook.getConsignee());
        //收货人电话
        orders.setPhone(addressBook.getPhone ());
        //收货地址（省名称+市名称+区名称+详细地址）
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName ())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName () == null ? "" : addressBook.getDistrictName())
                +(addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表内插入数据，一条
        ordersMapper.insert(orders);

        //向订单详情表插入数据，多条
        orderDetailService.saveBatch(orderDetailList);

        //清空登录用户的购物车
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

    }

    /**
     * 后台订单的分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime 开始时间（下单）
     * @param endTime   终止时间（下单）
     * @return
     */
    @Override
    public Page<Orders> page(Integer page, Integer pageSize,String number, String beginTime, String endTime) {

        //条件查询构造器
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.between(StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime), Orders::getOrderTime, beginTime, beginTime);
        lqw.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        lqw.orderByAsc(Orders::getStatus).orderByDesc(Orders::getOrderTime);
        //分页查询构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        ordersMapper.selectPage(ordersPage, lqw);

        return ordersPage;
    }

    /**
     * 查询当前用户的订单，并进行分页
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> userPage(Integer page, Integer pageSize) {
        //获取当前用户的id
        Long userId = BaseContext.getCurrentId();

        //创建Orders的分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, userId);
        //添加排序，使支付状态进度不高的排在前面，之后根据下单时间排序
        lqw.orderByAsc(Orders::getStatus).orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(ordersPage, lqw);

        //构建OrdersDto的分页构造器
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //对象拷贝，但不拷贝“records”
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        List<Orders> ordersList = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = ordersList.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            //因为ordersDto是新new出来的，其属性为空值，因此需要为其赋值
            BeanUtils.copyProperties(item, ordersDto);
            //查询订单的详细信息并为其Dto赋值
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, item.getNumber());
            List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetailList);

            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);

        return ordersDtoPage;
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public void again(Orders orders) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();

        //查询订单详情中的商品信息
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> orderDetailList = orderDetailService.list(lqw);
        if (orderDetailList == null || orderDetailList.size() == 0) {
            throw new RuntimeException("当前订单有误，请刷新页面！！！");
        }

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(item -> {
            //构建购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            //给购物车对象赋值
            //菜品、套餐名称
            shoppingCart.setName(item.getName());
            //图片
            shoppingCart.setImage(item.getImage());
            //用户id
            shoppingCart.setUserId(userId);
            //菜品id
            shoppingCart.setDishId(item.getDishId());
            //套餐id
            shoppingCart.setSetmealId(item.getSetmealId());
            //口味
            shoppingCart.setDishFlavor(item.getDishFlavor());
            //数量
            shoppingCart.setNumber(item.getNumber());
            //金额
            shoppingCart.setAmount(item.getAmount());
            //创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        //将购物车对象插入到数据库中
        shoppingCartService.saveBatch(shoppingCartList);
    }
}
